package com.stone.ws;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.stone.pojo.Message;
import com.stone.utils.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint(value = "/chat/{userName}", configurator = GetHttpSessionConfigurator.class)
@Component
@Slf4j
public class ChatEndpoint {
    // 用来存储每一个客户端对象对应的 ChatEndpoint 对象
    private static Map<String, ChatEndpoint> onLineUsers = new ConcurrentHashMap<>();

    // 声明 session 对象，通过该对象可以发送消息给指定的哦用户
    private Session session;

    // 声明一个 HttpSession 对象，我们之前在 HttpSession 对象中存储了用户名
    private HttpSession httpSession;


    /**
     * 连接建立时被调用
     *
     * @param session
     * @param config
     */
    // @OnOpen
    public void onOpen2(Session session, EndpointConfig config) throws IOException {
        // 将局部的 session 对象赋值给成员 session
        this.session = session;

        // 获取 httpSession 对象
        HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        this.httpSession = httpSession;

        // 将当前对象存储到 onLineUsers 容器中
        onLineUsers.put((String) httpSession.getAttribute("user"), this);

        // 将当前登录的用户名推送给所有的客户端
        String messge = "Hello !";
        Set<String> strings = onLineUsers.keySet();
        for (String name : strings) {
            ChatEndpoint chatEndpoint = onLineUsers.get(name);
            chatEndpoint.session.getBasicRemote().sendText(messge);
        }
    }


    //建立连接时发送系统广播
    @OnOpen
    public void onOpen(Session session, EndpointConfig config, @PathParam("userName") String userName) {
        this.session = session;
        /*HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        this.httpSession = httpSession;
        String username = (String) httpSession.getAttribute("user");*/
        log.info("上线用户名称：" + userName);
        onLineUsers.put(userName, this);
        String message = MessageUtils.getMessage(true, null, getNames());
        broadcastAllUsers(message);
    }

    //获取当前登录的用户
    private Set<String> getNames() {
        return onLineUsers.keySet();
    }

    //发送系统消息
    private void broadcastAllUsers(String message) {
        try {
            Set<String> names = onLineUsers.keySet();
            for (String name : names) {
                ChatEndpoint chatEndPoint = onLineUsers.get(name);
                chatEndPoint.session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收到客户端发送的数据时被调用
     *
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Message mess = mapper.readValue(message, Message.class);
            String toName = mess.getToName();
            String data = mess.getMessage();
            String username = mess.getFromName();
            log.info(username + "向" + toName + "发送的消息：" + data);
            String resultMessage = MessageUtils.getMessage(false, username, data);
            if (StringUtils.hasLength(toName)) {
                onLineUsers.get(toName).session.getBasicRemote().sendText(resultMessage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
